package com.imu.purse.api.controller;

import com.imu.common.annotation.IgnoreAuth;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.purse.config.PhoneValidate;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.form.RegisterForm;
import com.imu.purse.modules.app.service.CoreService;
import com.imu.purse.modules.app.service.ImuUserService;
import com.imu.purse.modules.base.entity.DictInfo;
import com.imu.purse.modules.base.service.DictInfoService;
import com.imu.purse.modules.bitcoin.YtfcoinApi;
import com.imu.purse.modules.sms.SMSCache;
import com.imu.purse.modules.sms.SMSMessage.Type;
import com.imu.utils.ShortUUID;
import com.qiniu.util.StringUtils;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 注册接口
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 17:27
 */

@RestController
@RequestMapping("/api")
@Api(tags="注册接口")
public class ApiRegisterController extends ApiAbstractController
{
    @Autowired
    private ImuUserService imuUserService;
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private SMSCache cache;
    
    @Autowired
    private YtfcoinApi ytfcoinApi;

    @Autowired
    private CoreService coreService;
    
    @Value("${spring.profiles.active}")
    private String active;

    @Autowired
    private DictInfoService dictInfoService;

    @IgnoreAuth
    @PostMapping("register")
    @ApiOperation("注册")
    public R register(HttpServletRequest request,@RequestBody RegisterForm form)
    {
        //表单校验
        ValidatorUtils.validateEntity(form);
        ImuUserEntity imuuser = imuUserService.queryByMobile(form.getPhone());
        if(imuuser!=null){
        	return ErrorUtil.errorMesg(request,ErrorDesc.PHONE_REG);
        }
        //验证图片验证码是否正确
        String picPass = form.getCode().toLowerCase();
        if(StrUtil.isEmpty(redisTemplate.opsForValue().get(picPass))){
            return ErrorUtil.errorMesg(request,ErrorDesc.PHOTO_ACODE_ERROR);
        }
        //验证手机验证码
        String type = String.valueOf(form.getType());
        Type messageType = PhoneValidate.Authentication(type);
        if(messageType == null) 
        {
        	return ErrorUtil.errorMesg(request,ErrorDesc.TYPE_ERR);
        }
        try
        {
        	String a = cache.findCode(messageType.getType(), form.getPhone());
        	if(!StringUtils.isNullOrEmpty(a)){
        		if(!a.equals(form.getCodes())){
        			return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
        		}
        	}else {
        		return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
			}
		}
        catch (Exception e) 
        {
        	return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
		}
        //随机选择核心钱包
        String moneyAddrStr = coreService.getCoreAddress();
        //调用以太坊创建账号  密码要使用UUID

        String ytfPwd = null;
        if(checkTranToOut()){//允许外部转账代表可以生成以太坊钱包地址
            ytfPwd = form.getPhone() + ShortUUID.shortUUID();
            String nAddress = ytfcoinApi.createAccount(ytfPwd,moneyAddrStr);
            if(StrUtil.isEmpty(nAddress)){
                return  ErrorUtil.errorMesg(request,ErrorDesc.SYSTEM_BUSY);
            }
            form.setMoneyAddress(nAddress);
        }
        //注册用户
        imuUserService.registerUser(form,moneyAddrStr,ytfPwd);
        //删除图片验证码
        redisTemplate.delete(picPass);
        //删除手机验证码
        cache.delCode(type,form.getPhone());
        return R.ok(1);
    }

    
    @IgnoreAuth
    @PostMapping("verificationCode")
    @ApiOperation("注册")
    public R verificationCode(HttpServletRequest request,String picPass)
    {
    	String que = redisTemplate.opsForValue().get(picPass);
        if(StringUtils.isNullOrEmpty(que)){
        	return ErrorUtil.errorMesg(request,ErrorDesc.PHOTO_ACODE_ERROR);
        }
    	return R.ok(1);
    }

    /**
     * 校验是否允许转出到外部 只有外部转账的，才允许创建以太坊账号
     * @return
     */
    private boolean checkTranToOut(){
        boolean outFlag = true; //默认允许转出到其他核心钱包
        List<DictInfo> dictList = dictInfoService.findCahceByCode("TRANS_OUT_FLAG");
        if(!CollectionUtils.isEmpty(dictList)) {
            for (DictInfo dic : dictList) {
                if (dic.getLabel().equals("OUT_FLAG")) {
                    if(Integer.valueOf(dic.getValue()) == 0){//不允许外部转账
                        outFlag = false;
                    }
                    break;
                }
            }
        }
        return outFlag;
    }
}
